package com.bb.blog.security.model;

import com.bb.blog.security.constant.UserConstant;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


public class BbUserDetail implements UserDetails {
    private static final long serialVersionUID = -7560842650383658643L;
    private User user;
    private List<GrantedAuthority> grantedAuthorityList;


    public BbUserDetail(User user, List<Resources> resources) {
        this.user = user;
        List<GrantedAuthority> authorities = resources.stream().map(
            r -> new SimpleGrantedAuthority(r.getSystemCode().toUpperCase() + "_" + r.getCode())).collect(Collectors.toList());
        grantedAuthorityList = authorities;


    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return grantedAuthorityList;


    }

    public User getUser() {
        return user;
    }


    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return !UserConstant.USER_DELETE.equals(user.getStatus());
    }

    @Override
    public boolean isAccountNonLocked() {
        return !UserConstant.USER_FREEZE.equals(user.getStatus());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return UserConstant.USER_NORMAL.equals(user.getStatus());
    }
}
